package com.gmail.dengtao.joe.commons.crypto.cipher;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

/**
 * Encrypt/decrypt input using the AES Cipher.
 * @author <a href="mailto:joe.dengtao@gmail.com">DengTao</a>
 * @version 1.0
 * @since 1.0
 */
public class AES {

	private String transformation = CipherUtils.AES;
	
	public AES(String transformation) {
    	this.transformation = transformation;
    }
	
    public AES(String mode, String padding) {
    	transformation = CipherUtils.AES + "/" + mode + "/" + padding;
	}

	public byte[] encrypt(byte[] data, byte[] key) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
        return process(data, key, Cipher.ENCRYPT_MODE);
    }

    public byte[] decrypt(byte[] data, byte[] key) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
        return process(data, key, Cipher.DECRYPT_MODE);
    }

    private byte[] process(byte[] data, byte[] key, int type) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, CipherUtils.AES);
        Cipher cipher = CipherUtils.getCipher(transformation);
        cipher.init(type, secretKeySpec);
        return cipher.doFinal(data);
    }

}